package main;

import java.util.Random;

//Nikolas Wolfe
//2/20/09
//CIS 4930
//Candybox

// This class implements the functionality of the CandyBox

public class CandyBox
{
	private final int size;
	private Candy[] box;
	private final Random rnd = new Random();
	
	public CandyBox( int n )
	{
		this.size = n;
		this.box = new Candy[size];
		for(int i = 0; i < size; ++i)
		{
			box[i] = new Candy();
		}
	}
	
	public synchronized Candy sampleCandy( CandySamplerThread cst ) 
		throws InterruptedException
	{
		int i; 
		while(box[(i = rnd.nextInt(box.length))] == null)
		{
			this.wait(); // don't block another thread
		} 
		Candy candy = box[i];
		box[i] = null;
		System.out.println( cst.toString() + 
				" retrieved Candy #" + candy.getId());
		return candy;
	}
	
	public synchronized void returnCandy( CandySamplerThread cst, Candy candy )
	{
		// it's impossible that we're returning a candy and there's no
		// available space
		for(int i = 0; i < size; ++i)
		{
			if( box[i] == null )
			{
				box[i] = candy;
				break;
			}
		}
		System.out.println( cst.toString() + 
				" returned Candy #" + candy.getId());
		this.notifyAll(); // multiple threads can benefit
	}
	
	// synchronized so that box state is preserved 
	// throughout the iteration
	public synchronized void printStatus()
	{
		for(int i = 0; i < size; ++i)
		{
			System.out.println( box[i].toString() + " is " + 
					box[i].getStatus());
		}
	}
	
	public int getCapacity()
	{
		return size;
	}
}
